package com.wechat.network;

import com.swak.config.setting.Settings;
import com.swak.exception.StaleObjectStateException;
import com.swak.utils.StringUtils;
import com.wechat.Cons;
import com.wechat.enums.Models;
import com.wechat.network.peer.PeerNetwork;
import com.wechat.network.remote.RemoteNetwork;

/**
 * Networks.
 * 
 * @author 618lf
 */
public class Networks {

	private static Network Instance = null;

	public static Network New() {
		if (Instance == null) {
			synchronized (Networks.class) {
				if (Instance == null) {
					Settings setting = Settings.intSettings();
					String model = setting.getConfig(Cons.Network_Model_Key);
					if (StringUtils.isBlank(model) || Models.P2P.name().equals(model)) {
						Instance = NewPeerNetwork(setting);
					} else {
						Instance = NewRemoteNetwork(setting);
					}
				}
			}
		}
		return Instance;
	}

	private static Network NewPeerNetwork(Settings setting) {
		String ser = setting.getConfig(Cons.Network_Sers_Key);
		return new PeerNetwork(ser, NetworkHandler.newNetworkHandler());
	}

	private static Network NewRemoteNetwork(Settings setting) {
		String ser = setting.getConfig(Cons.Network_Sers_Key);
		if (StringUtils.isBlank(ser)) {
			throw new StaleObjectStateException("请设置服务地址！");
		}

		return new RemoteNetwork(ser, NetworkHandler.newNetworkHandler());
	}
}
